package com.leetcode.二分查找;

public class lc_34 {
    public int[] searchRange(int[] nums, int target) {
        int start = lowerBound(nums, target);
        if(start == nums.length || nums[start] != target){
            return new int[]{-1, -1};
        }
        int end = lowerBound(nums, target + 1) - 1;
        return new int[]{start, end};
    }
    //二分查找的方法, 返回第一个 >= target的位置,
    //那么返回最后一个 >= target的位置就是第一个 >= target - 1的位置 -1
    private int lowerBound(int[] nums, int target){
        int left = -1;
        int right = nums.length;
        while(left + 1 < right){
            int mid = left + (right - left) / 2;
            if(target <= nums[mid]){
                right = mid;
            } else{
                left = mid;
            }
        }
        return left + 1;
    }
}
